<?php
/**
 * Created by PhpStorm.
 * User: lzhy@lzhy.me
 * Date: 2019/4/12 0012
 * Time: 14:33
 */
namespace app\admin\controller;

use app\admin\event\Dt;
use app\admin\event\Utils;
use think\Db;
use think\facade\Request;

class Permission extends Base
{
    public function index()
    {
        if(Request::isPost()){
            $dt = new Dt();
            $data = $dt->table('permission')->searchField('name,mark,path')->fetch();
            foreach ($data['data'] as &$v){
                $editAction   = url('edit',['id'=>$v['id']]);
                $removeAction = url('del',['id'=>$v['id']]);
                $v['buttons'] = sprintf('<a href="#" class="btn-edit" data-action="%s"><i class="fa fa-edit"></i></a>&nbsp;&nbsp;<a href="#" class="btn-remove" data-action="%s"><i class="fa fa-remove"></i></a>',$editAction,$removeAction);
                if($v['method']){
                    $v['method'] = join('&nbsp;',array_map(function($v){
                        return '<span class="label label-primary">'.$v.'</span>';
                    },explode(',',$v['method'])));
                }else{
                    $v['method'] = '<span class="label label-primary">ANY</span>';
                }
                $v['path'] = join('',array_map(function($v){
                    return '<div><code>'.$v.'</code></div>';
                },explode(',',$v['path'])));
            }
            exit(json_encode($data));
        }

        $tColumns = [
            ['data'=>'id','title'=>'自动编号','orderable'=>true],
            ['data'=>'name','title'=>'名称','orderable'=>false],
            ['data'=>'mark','title'=>'标识','orderable'=>false],
            ['data'=>'method','title'=>'方法','orderable'=>false],
            ['data'=>'path','title'=>'路径','orderable'=>false],
            ['data'=>'add_time','title'=>'添加时间'],
            ['data'=>'buttons','title'=>'操作','orderable'=>false],
        ];
        $this->assign(['columns'=>json_encode($tColumns)]);
        return view();
    }

    public function edit()
    {
        if(Request::isPost()){
            $params = Request::param();
            $res = ['success'=>0,'msg'=>'请填写完整后再提交'];
            if($params['name'] && $params['mark'] && $params['path']){
                $id = $params['id'];
                try{
                    $data = [
                        'name' => $params['name'],
                        'mark' => $params['mark'],
                        'path' => join(',',preg_split('/\s+/',trim($params['path']))),
                        'update_time' => date('Y-m-d H:i:s')
                    ];
                    if(isset($params['method'])){
                        $data['method'] = join(',',$params['method']);
                    }

                    if($id){
                        $rel = Db::table('permission')->where('id',$id)->update($data);
                        $res = ['success'=>0,'msg'=>'更新失败，请重试'];
                        if($rel){
                            $res = ['success'=>1,'msg'=>'更新成功'];
                        }
                    }else{
                        $data['add_time'] = date('Y-m-d H:i:s');
                        $rel = Db::table('permission')->insert($data);
                        $res = ['success'=>0,'msg'=>'添加失败，请重试'];
                        if($rel){
                            $res = ['success'=>1,'msg'=>'添加成功'];
                        }
                    }
                }catch (\Exception $e){
                    $res = ['success'=>0,'msg'=>'操作失败，请稍后再试','err'=>$e->getMessage()];
                }
            }
            Utils::ifrResponse($res);
        }

        $id = Request::param('id');
        $data = [];
        if($id){
            $data = Db::table('permission')->where('id',$id)->find();
            $data['path']   = str_replace(',',PHP_EOL,$data['path']);
            $data['method'] = explode(',',$data['method']);
            $this->assign('data',$data);
        }
        
        $field = [
            ['label'=>'','name'=>'id','type'=>'hidden'],
            ['label'=>'标识','name'=>'mark'],
            ['label'=>'名称','name'=>'name'],
            ['label'=>'HTTP方法','name'=>'method','type'=>'select2','options'=>[
                'GET' => 'GET',
                'POST' => 'POST',
                'PUT' => 'PUT',
                'DELETE' => 'DELETE',
                'PATCH' => 'PATCH',
                'OPTIONS' => 'OPTIONS',
                'HEAD' => 'HEAD'
            ],'multiple'=>true,'tips'=>'<span class="form-text m-b-none text-warning">为空默认为所有方法</span>'],
            ['label'=>'HTTP路径','name'=>'path','type'=>'textarea'],
        ];
        return parent::_buildModalEditForm('用户编辑',$field,$data);
        return view();
    }

    public function del()
    {
        $id = Request::param('id');
        Utils::rowDel('permission',$id);
    }
}